<template>
  <div>
    <el-dialog
      title="退款管理"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-date-picker
          v-model="timerange"
          type="datetimerange"
          value-format="timestamp"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          :default-time="['0:00:00', '23:59:59']"
          end-placeholder="结束日期"
        />
        <el-select v-model="approved_state" placeholder="审批状态">
          <el-option value="" label="所有" />
          <el-option
            v-for="item in approved_states"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="selected_status" clearable>
          <el-option
            v-for="(item,index) in status_opitons"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="kwInput"
          placeholder="输入交易ID或者单号进行搜索"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button icon="el-icon-plus" @click="handleAction('create')">添加</el-button>
      </div>

      <el-table
        v-loading.fullscreen.lock="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        show-summary
        @sort-change="handleSort"
      >
        <el-table-column align="center" label="支付公司" prop="payment_name" width="240px">
          <template slot-scope="scope">
            <span style="display: block">支付:{{ scope.row.payment_name }}</span>
            <span style="display: block">账号:{{ scope.row.payment_account }}</span>
            <span style="display: block">交易:{{ scope.row.id_transaction }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单信息" width="240px">
          <template slot-scope="scope">
            <span style="display: block">网站:{{ scope.row.domain }}</span>
            <span style="display: block">订单:{{ scope.row.id_order }}</span>
            <span style="display: block">系统单号:{{ scope.row.psorders_id }}<i class="el-icon-search" style="color: red" @click="emitSearchOrder(scope.row.psorders_id)" /></span>
            <span style="display: block">金额:{{ scope.row.order_amount }}</span>
            <span style="display: block">经理:{{ scope.row.manager }}</span>

          </template>
        </el-table-column>
        <el-table-column align="center" label="退款金额" prop="refund_amount" sortable="custom">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.refund_amount === scope.row.order_amount" type="success">{{ scope.row.refund_amount }}</el-tag>
            <el-tag v-else-if="scope.row.refund_amount > scope.row.order_amount" type="danger">{{ scope.row.refund_amount }}</el-tag>
            <el-tag v-else-if="scope.row.refund_amount < scope.row.order_amount" type="warning">{{ scope.row.refund_amount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="note" prop="note" sortable="custom" />
        <el-table-column align="center" label="审批" prop="approved_state" sortable="custom">
          <template slot-scope="scope">
            <el-select v-model="scope.row.approved_state" placeholder="审批状态" @change="handleChangeApproveState(scope.row)">
              <el-option
                v-for="item in approved_states"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" prop="is_finished" sortable="custom">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_finished"
              title="是否已经关闭"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleChangeState(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作人" prop="operator" sortable="custom" />
        <el-table-column align="center" label="创建时间" prop="create_at" sortable="custom" />
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-dialog>
    <el-dialog
      append-to-body
      :title="inner_title"
      :visible.sync="innerDialogVisuble"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="200px">
        <el-form-item label="Payment ID">
          <el-input v-model="temp.payment_id" disabled />
        </el-form-item>
        <el-form-item label="退款金额">
          <el-input v-model="temp.refund_amount" />
        </el-form-item>
        <el-form-item label="退款原因">
          <el-input v-model="temp.note" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisuble = false">取 消</el-button>
        <el-button @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Delete, Put, Post } from '@/api/orders/orderrefund'

import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Refund',
  props: ['orderrefundVisual', 'psorderpayment_id', 'title'],
  data() {
    return {
      approved_state: '',
      inner_title: '新增退款',
      innerDialogVisuble: false,
      data: [],
      timerange: '',
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime())
            start.setHours(0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天下班后',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            start.setHours(19, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '过去14天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近6个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近1年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }
        ]
      },
      selected_status: 'unfinished',
      approved_states: [
        {
          'name': '通过',
          'value': 2
        },
        {
          'name': '等待审核',
          'value': 1
        },
        {
          'name': '拒绝',
          'value': 3
        }
      ],
      status_opitons: [
        {
          'name': '完成',
          'value': 'finished'
        },
        {
          'name': '未完成',
          'value': 'unfinished'
        },
        {
          'name': '所有',
          'value': ''
        }
      ],
      dialogVisible: false,
      listLoading: true,
      action: '',
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      temp: {
        payment_id: '',
        is_finished: false,
        refund_amount: 0,
        note: ''
      }
    }
  },
  watch: {
    orderrefundVisual(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
      }
    },
    psorderpayment_id(v) {
      if (v !== '') {
        this.action = 'create'
        this.innerDialogVisuble = true
      }
      this.temp.payment_id = v
    },
    title(v) {
      this.inner_title = v
    }
  },
  methods: {
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        status: this.selected_status,
        start: this.timerange ? this.timerange[0] : '',
        end: this.timerange ? this.timerange[1] : '',
        approved_state: this.approved_state,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    resetTemp() {
      this.temp = {
        payment_id: '',
        is_finished: false,
        refund_amount: 0,
        note: ''
      }
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.innerDialogVisuble = true
          this.resetTemp()
          break
        case 'edit':
          this.temp.id = row.id
          this.temp.payment_id = row.payment_id
          this.temp.is_finished = row.is_finished
          this.temp.refund_amount = row.refund_amount
          this.temp.note = row.note
          this.innerDialogVisuble = true
          break
        case 'delete':
          this.innerDialogVisuble = true
          this.temp = row
          break
      }
    },
    confirm() {
      console.log('clcik cofnirm', this.action)
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data).then(response => {
            this.innerDialogVisuble = false
            this.resetTemp()
            this.getList()
            this.notify('添加成功')
          })
          return
        case 'edit':
          Put(_data.id, _data).then(response => {
            this.innerDialogVisuble = false
            this.resetTemp()
            this.getList()
            this.notify('更新成功')
          })
          return
        case 'delete':
          Delete(_data.id).then((response) => {
            this.innerDialogVisuble = false
            this.resetTemp()
            this.getList()
            this.notify('删除成功')
          })
          return
      }
    },
    handleChangeState(row) {
      this.$confirm(`确认修改退款完成状态  ${row.id_order}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Put(row.id, { id: row.id, is_finished: row.is_finished }).then(response => {
          this.notify('修改成功')
        })
      }).catch(() => {
        row.is_finished = !row.is_finished
      })
    },
    emitSearchOrder(id) {
      this.dialogVisible = false
      this.$emit('searchOrder', id)
    },
    handleChangeApproveState(row) {
      Put(row.id, row).then(response => {
        this.innerDialogVisuble = false
        this.getList()
        this.notify('修改成功')
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMyDialog', false)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-input {
  width: auto;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 5px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 5px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin: 10px auto !important;
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 60px;
  padding-top: 5px;
}

.top >>> .el-select {
  width: 300px;
}
</style>
